<?php

namespace app\jigou\controller\qingdongams\parts;

use addons\qingdongams\model\Account;
use addons\qingdongams\model\Contacts;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\File;
use addons\qingdongams\model\Form;
use addons\qingdongams\model\Message;
use addons\qingdongams\model\Parts as PartsModel;
use addons\qingdongams\model\PartsStock;
use addons\qingdongams\model\PartsStockReload;
use addons\qingdongams\model\Staff;
use app\jigou\controller\qingdongams\Base;
use addons\qingdongams\model\Product;
use think\Db;
use think\Exception;

/**
 * 备件管理
 * @icon fa fa-user
 */
class Parts extends Base {
	protected $relationSearch = true;
	protected $searchFields   = 'id,name,num';
	/**
	 * @var \addons\qingdongams\model\Parts
	 */
	protected $model = null;


	public function _initialize() {
		parent::_initialize();
		$this->model = new \addons\qingdongams\model\Parts;
	}


	/**
	 * 查看
	 */
	public function index() {
		//设置过滤方法
		$this->request->filter(['strip_tags', 'trim']);
		if ($this->request->isAjax()) {

			list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//
			//负责人为空
			$list = $this->model->where($where)->order($sort, $order)->paginate($limit);

			$result = array("total" => $list->total(), "rows" => $list->items());

			return json($result);
		}

		return $this->view->fetch();
	}


	/**
	 * 添加
	 */
	public function add() {
		if ($this->request->isPost()) {
			$params = $this->request->post("row/a");
			if ($params) {
				$params = $this->preExcludeFields($params);

                $params['product_id']=implode(',',$params['product_id']);
				$result = false;
				Db::startTrans();
				try {
					$result = $this->model->allowField(true)->save($params);
					Db::commit();
				} catch (Exception $e) {
					Db::rollback();
					$this->error($e->getMessage());
				}
				if ($result !== false) {
					$this->success();
				} else {
					$this->error(__('No rows were inserted'));
				}
			}
			$this->error(__('Parameter %s can not be empty', ''));
		}
		$product=Product::where([])->column('name','id');

		$this->view->assign('product',$product);
		return $this->view->fetch();
	}

	//修改
	public function edit($ids = null) {
		$map['id'] = $ids;
		if ($this->request->isAjax()) {
			$params = $this->request->post('row/a');
			$params = $this->preExcludeFields($params);
            $params['product_id']=implode(',',$params['product_id']);
			$result = false;
			Db::startTrans();
			try {
				$result = $this->model->allowField(true)->update($params, $map);
				Db::commit();
			} catch (Exception $e) {
				Db::rollback();
				$this->error($e->getMessage());
			}
			if ($result !== false) {
				$this->success('修改成功');
			} else {
				$this->error('修改失败');
			}
		}
		$data = $this->model->where($map)->find()->getData();
		$this->view->assign("row", $data);
        $product=Product::where([])->column('name','id');

        $this->view->assign('product',$product);
		return $this->view->fetch();
	}


	public function detail($ids=null){
		$row=$this->model->where(['id'=>$ids])->find();

		$this->assign('row',$row);
		$this->assign('ids',$ids);
		return $this->view->fetch();
	}

	/**
	 * 删除
	 */
	public function del($ids = "") {
		if (!$this->request->isPost()) {
			$this->error(__("Invalid parameters"));
		}
		$ids                 = $ids ? $ids : $this->request->post("ids");
		$row                 = $this->model->get($ids);
		$this->modelValidate = true;
		if (!$row) {
			$this->error(__('No Results were found'));
		}
		$row->delete();
		$this->success();
	}

    /**
     * 出库
     */
    public function export($ids = null) {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $parts = PartsModel::where(['id' => $ids])->with(['createStaff'])->find();
                $result = false;
                Db::startTrans();
                try {
                    $parts['number'] = $params['number'];
                    unset($params['number']);
                    $params['parts'][] = $parts;
                    $params['type'] = 2;
                    $params['parts'] = json_encode($params['parts']);

                    PartsStockReload::addRecord($params);
                    Db::commit();
                    $this->success();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $parts = PartsModel::where(['id' => $ids])->with(['createStaff'])->find();
        if (!empty($parts['product_id'])) {
            $product_ids = explode(',', $parts['product_id']);
            $names = \addons\qingdongams\model\Product::where(['id' => ['in', $product_ids]])->column('name');
            $parts['product_name'] = implode(',', $names);
        }
        $parts['stocks'] = PartsStock::where(['parts_id' => $ids])->with(['createStaff'])->select();
        $this->assign('parts', $parts);
        $this->assign('ids', $ids);
        $this->assign('staffs', Staff::getList());
        $this->assign('number', getItemNumber('export'));
        return $this->view->fetch();
    }
    /**
     * 入库
     */
    public function import($ids = null) {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $parts = PartsModel::where(['id' => $ids])->with(['createStaff'])->find();
                Db::startTrans();
                try {
                    $parts['number'] = $params['number'];
                    unset($params['number']);
                    $params['parts'][] = $parts;
                    $params['type'] = 1;
                    $params['parts'] = json_encode($params['parts']);

                    PartsStockReload::addRecord($params);
                    Db::commit();
                    $this->success();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $parts = PartsModel::where(['id' => $ids])->with(['createStaff'])->find();
        if (!empty($parts['product_id'])) {
            $product_ids = explode(',', $parts['product_id']);
            $names = \addons\qingdongams\model\Product::where(['id' => ['in', $product_ids]])->column('name');
            $parts['product_name'] = implode(',', $names);
        }
        $parts['stocks'] = PartsStock::where(['parts_id' => $ids])->with(['createStaff'])->select();
        $this->assign('parts', $parts);
        $this->assign('ids', $ids);
        $this->assign('staffs', Staff::getList());
        $this->assign('number', getItemNumber('import'));
        return $this->view->fetch();
    }

    /**
     * 审批记录
     */
    public function logs() {
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            $this->relationSearch = true;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams(null, null);

            $ids=input('ids');
            if ($ids) {
                $reloads = PartsStockReload::where(['create_staff_id'=>$this->_staff->id])->column('id');
                $wheres['relation_id'] =['in',$reloads];
            }
            $wheres['relation_type'] = 'parts';
            $list   =  (new ExamineRecord())->where($where)->where($wheres)->with([
                'checkStaff',
                'parts' => ['createStaff']
            ])->order('id', $order)->paginate($limit);
            $row    = $list->items();

            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 出入库记录
     */
    public function get_stock_record()
    {
        if ($this->request->isAjax()) {
            $limit = 10;
            $page = $this->request->post('pageNumber');
            $ids = input('ids');
            $type = input('type');

            if (empty($ids)) {
                $this->error('库存不存在');
            }
            $where = [];
            if ($type) {
                $where['type'] = $type;
            }
            if ($ids) {
                $where['parts_id'] = $ids;
            }
            $stocks = PartsStock::where($where)->with(['parts', 'createStaff'])->paginate($limit, false, ['page' => $page]);
            $stocks = $stocks->toArray();

            return json(['rows' => $stocks['data'], 'total' => $stocks['total']]);
        }
    }

    public function log_info($ids = null)
    {
        $types = input('types','parts');
        $row = PartsStockReload::where(['id' => $ids])->find();
        if ($row['check_status'] == 0 || $row['check_status'] == 1) {
            $row['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::PARTS_TYPE, $ids);
        } else {
            $row['is_examine'] = 0;
        }

        $this->assign('row', $row);
        $this->assign('ids', $ids);
        $examin = ExamineRecord::with('checkStaff')->where(array('relation_id' => $ids, 'relation_type' => 'parts'))->select();
        foreach ($examin as $k => $v) {
            switch ($v['status']) {
                case 0:
                    $examin[$k]['status_name'] = '待审批';
                    break;
                case 1:
                    $examin[$k]['status_name'] = '审核通过';
                    break;
                case 2:
                    $examin[$k]['status_name'] = '审核拒绝';
                    break;
                case 3:
                    $examin[$k]['status_name'] = '撤销';
                    break;
                default:
                    $examin[$k]['status_name'] = '待审批';
                    break;
            }
        }
        Message::setRead($types,$ids,$this->_staff->id);
        $this->assign('examin', $examin);
        return $this->view->fetch();
    }
}
